<template>
  <div>
    <el-select ref="selectRef" v-model="param.selectCity" clearable filterable remote reserve-keyword
      :multiple="multiple" :multiple-limit="multipleLimit" :remote-method="getCityList" :disabled="disabled"
      @change="cityDataChange" @clear="clear" :loading="param.loading" style="width:100%" placeholder="请输入城市">
      <el-option v-for="item in param.cityOptions" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, watch } from 'vue';
import { getCity } from '../../api/system/city'; // 引入城市接口   remove-tag
const emit = defineEmits(['cityId', 'clear', 'cityInfo', 'beforeChange'])
const props = defineProps({  // 默认情况下，一个组件上的 v - model 会把 value 用作 prop 且把 input 用作 event
  selectCity: {
    type: String,
    default: ''
  },
  inChina:{
    type: Number,
    default: 0
  },
  disabled: {
    type: Boolean,
    default: false
  },
  needInfo: {
    type: Boolean,
    default: false
  },
valueSel: {
    type: Boolean,
    default: false
  },
  
  cityList: {
    type: Array,
    default: () => {
      return []
    }
  },
  multiple: {
    type: Boolean,
    default: false
  },
  multipleLimit: {
    type: Number,
    default: 0
  },
  needBeforeChange: {
    type: Boolean,
    default: false
  },
  index:{ // 当前修改数据行的下标
    type:Number,
    default: 0
  }
})

// 监听更新param.selectCity
watch(() => props.cityList, (list: any) => {
  setSelectCity(list)
}, { deep: true });

watch(() => props.selectCity, (val: any) => {
  param.selectCity = val
}, { deep: true })

const param = reactive({
  loading: false,
  cityOptions: [],
  selectCity: props.value,
  infos: []
})

//城市赋值
const setSelectCity = (list: any) => {
  if (list && list.length > 0) {
    param.cityOptions = list
    param.selectCity = props.multiple ? list.map((item: any) => item.value) : list[0].value
  } else {
    param.selectCity = props.multiple ? [] : ''
  }
}

// 获取城市列表
const selectRef = ref()
const getCityList = (query: string) => {
  if (!query) return
  param.loading = true 
  let data={}
  if(props.inChina!=0){  
    // 5 中国 10国外
    data={ cityCName: query,cityType:props.inChina}
  }else{
    data={ cityCName: query}
  }
  getCity(data).then((res: any) => {
    param.loading = false
    let cityOptions = res.data.map((item: any) => {
      return { value: item.id, label: item.cityCName, countryCName: item.countryCName, countryId: item.countryId }
    })
    if (props.multiple && param.cityOptions.length > 0) { //多选城市时，若param.cityOptions原本有数据（编辑场景）,则加入 检索的城市列表中
      cityOptions.forEach((item: any) => {
        let index = param.cityOptions.findIndex((val: any) => val.value === item.value)
        if (index === -1) {
          param.cityOptions.push(item)
        }
      })
    } else {
      param.cityOptions = cityOptions
    }
  }).catch((err: any) => {
    console.log(err)
    param.loading = false
  })
}

// 清空 迭代中
const clear = (val: any) => {
  if (props.multiple) { //多选

  } else {//单选
    emit('clear')
  }
}

// 城市变更
const cityDataChange = async (select: any) => {
  if (props.valueSel) {
    return emit('cityId', select)
  }
  if (!select) return
  if (!props.needInfo) {
    return emit('cityId', select)
  }
  if (props.multiple) { //多选
    param.infos = seletCityInfoList(select)
    emit('cityId', select, param.infos)
    emit('cityInfo', param.infos)
  } else { //单选
    let info = param.cityOptions.filter((item: any) => item.value === select).map((item: any) => {
      return { cityCName: item.label, id: item.value, countryCName: item.countryCName, countryId: item.countryId }
    })
    emit('cityId', select, info[0],props.index)
    emit('cityInfo', info[0])
  }
}

// 多选 整理选中城市信息
const seletCityInfoList = (select: any) => {
  let list: [] = []
  let cityOptions=[]
  select.forEach((el: any) => {
    param.cityOptions.forEach((item: any) => {
      if (el == item.value) {
        let listItem = { 
          cityCName: item.label, 
          id: item.value, 
          countryCName: item.countryCName, 
          countryId: item.countryId 
        }
        cityOptions.push(item)
        list.push(listItem)
      }
    })
  })
   param.cityOptions=cityOptions
  return list
}

const clearSelectCity = () => { 
  param.selectCity = ""
}

defineExpose({
  setSelectCity,
  clearSelectCity,
})
</script>
<style lang="scss" scoped></style>